<template>
  <div class="book-management">
    <ManagementTable
      ref="managementTableRef"
      :search-label="'搜索'"
      :search-placeholder="'书名、作者或分类'"
      :table-title="'书籍管理'"
      :table-data="bookList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      :item-name="'书籍'"
      :show-add-button="true"
      @search="searchBooks"
      @reset="resetSearch"
      @add="showAddBookDialog"
      @edit="showEditBookDialog"
      @delete="deleteBook"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      table-width="100%"
    >
      <template #status="{ row }">
        <el-tag :type="row.status === '连载' ? 'success' : 'info'">
          {{ row.status }}
        </el-tag>
      </template>
      
      <template #isVip="{ row }">
        <el-tag :type="row.isVip === 1 ? 'warning' : 'success'">
          {{ row.isVip === 1 ? 'VIP' : '免费' }}
        </el-tag>
      </template>
      
      <template #targetUser="{ row }">
        <el-tag v-if="row.targetUser === 0">通用</el-tag>
        <el-tag v-else-if="row.targetUser === 1" type="primary">男生</el-tag>
        <el-tag v-else-if="row.targetUser === 2" type="danger">女生</el-tag>
        <span v-else>{{ row.targetUser }}</span>
      </template>
      
      <template #createTime="{ row }">
        {{ formatDateTime(row.createTime) }}
      </template>
    </ManagementTable>

    <!-- 添加书籍对话框 -->
    <el-dialog v-model="addBookDialogVisible" title="添加书籍" width="600px">
      <el-form :model="addBookForm" :rules="addBookRules" ref="addBookFormRef" label-width="120px">
        <el-form-item label="书名" prop="novelName">
          <el-input v-model="addBookForm.novelName" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="addBookForm.author" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="addBookForm.category" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addBookForm.status" placeholder="请选择状态">
            <el-option label="连载" value="连载" />
            <el-option label="完结" value="完结" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否VIP" prop="isVip">
          <el-select v-model="addBookForm.isVip" placeholder="请选择是否VIP">
            <el-option label="免费" :value="0" />
            <el-option label="VIP" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标用户" prop="targetUser">
          <el-select v-model="addBookForm.targetUser" placeholder="请选择目标用户">
            <el-option label="通用" :value="0" />
            <el-option label="男生" :value="1" />
            <el-option label="女生" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="小说简介" prop="intro">
          <el-input v-model="addBookForm.intro" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="封面URL" prop="coverUrl">
          <el-input v-model="addBookForm.coverUrl" />
        </el-form-item>
        <el-form-item label="主页链接" prop="novelUrl">
          <el-input v-model="addBookForm.novelUrl" />
        </el-form-item>
        <el-form-item label="最新章节" prop="latestChapter">
          <el-input v-model="addBookForm.latestChapter" />
        </el-form-item>
        <el-form-item label="章节链接" prop="chapterUrl">
          <el-input v-model="addBookForm.chapterUrl" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-input v-model="addBookForm.updateTime" />
        </el-form-item>
        <el-form-item label="点击量" prop="clickCount">
          <el-input-number v-model="addBookForm.clickCount" :min="0" />
        </el-form-item>
        <el-form-item label="订阅量" prop="subscribeCount">
          <el-input-number v-model="addBookForm.subscribeCount" :min="0" />
        </el-form-item>
        <el-form-item label="推荐量" prop="recommendCount">
          <el-input-number v-model="addBookForm.recommendCount" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addBookDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addBook">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑书籍对话框 -->
    <el-dialog v-model="editBookDialogVisible" title="编辑书籍" width="600px">
      <el-form :model="editBookForm" :rules="editBookRules" ref="editBookFormRef" label-width="120px">
        <el-form-item label="书籍ID" prop="bookId">
          <el-input v-model="editBookForm.bookId" disabled />
        </el-form-item>
        <el-form-item label="书名" prop="novelName">
          <el-input v-model="editBookForm.novelName" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="editBookForm.author" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="editBookForm.category" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editBookForm.status" placeholder="请选择状态">
            <el-option label="连载" value="连载" />
            <el-option label="完结" value="完结" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否VIP" prop="isVip">
          <el-select v-model="editBookForm.isVip" placeholder="请选择是否VIP">
            <el-option label="免费" :value="0" />
            <el-option label="VIP" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标用户" prop="targetUser">
          <el-select v-model="editBookForm.targetUser" placeholder="请选择目标用户">
            <el-option label="通用" :value="0" />
            <el-option label="男生" :value="1" />
            <el-option label="女生" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="小说简介" prop="intro">
          <el-input v-model="editBookForm.intro" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="封面URL" prop="coverUrl">
          <el-input v-model="editBookForm.coverUrl" />
        </el-form-item>
        <el-form-item label="主页链接" prop="novelUrl">
          <el-input v-model="editBookForm.novelUrl" />
        </el-form-item>
        <el-form-item label="最新章节" prop="latestChapter">
          <el-input v-model="editBookForm.latestChapter" />
        </el-form-item>
        <el-form-item label="章节链接" prop="chapterUrl">
          <el-input v-model="editBookForm.chapterUrl" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-input v-model="editBookForm.updateTime" />
        </el-form-item>
        <el-form-item label="点击量" prop="clickCount">
          <el-input-number v-model="editBookForm.clickCount" :min="0" />
        </el-form-item>
        <el-form-item label="订阅量" prop="subscribeCount">
          <el-input-number v-model="editBookForm.subscribeCount" :min="0" />
        </el-form-item>
        <el-form-item label="推荐量" prop="recommendCount">
          <el-input-number v-model="editBookForm.recommendCount" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editBookDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateBook">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import ManagementTable from '@/components/admin/ManagementTable.vue'

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 书籍列表
const bookList = ref([])
const loading = ref(false)

// 管理表格引用
const managementTableRef = ref(null)

// 表格列定义
const columns = [
  { prop: 'bookId', label: '书籍ID', width: 80 },
  { prop: 'novelName', label: '书名' },
  { prop: 'author', label: '作者' },
  { prop: 'category', label: '分类' },
  { prop: 'status', label: '状态', width: 100, slot: 'status' },
  { prop: 'isVip', label: '是否VIP', width: 100, slot: 'isVip' },
  { prop: 'targetUser', label: '目标用户', width: 100, slot: 'targetUser' },
  { prop: 'createTime', label: '创建时间', width: 180, slot: 'createTime' }
]

// 添加书籍对话框可见性
const addBookDialogVisible = ref(false)

// 编辑书籍对话框可见性
const editBookDialogVisible = ref(false)

// 添加书籍表单
const addBookForm = reactive({
  novelName: '',
  author: '',
  category: '',
  status: '连载',
  isVip: 0,
  targetUser: 0,
  intro: '',
  coverUrl: '',
  novelUrl: '',
  latestChapter: '',
  chapterUrl: '',
  updateTime: '',
  clickCount: 0,
  subscribeCount: 0,
  recommendCount: 0
})

// 编辑书籍表单
const editBookForm = reactive({
  bookId: null,
  novelName: '',
  author: '',
  category: '',
  status: '连载',
  isVip: 0,
  targetUser: 0,
  intro: '',
  coverUrl: '',
  novelUrl: '',
  latestChapter: '',
  chapterUrl: '',
  updateTime: '',
  clickCount: 0,
  subscribeCount: 0,
  recommendCount: 0
})

// 添加书籍表单引用
const addBookFormRef = ref(null)

// 编辑书籍表单引用
const editBookFormRef = ref(null)

// 添加书籍表单验证规则
const addBookRules = {
  novelName: [
    { required: true, message: '请输入书名', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入分类', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  isVip: [
    { required: true, message: '请选择是否VIP', trigger: 'change' }
  ],
  targetUser: [
    { required: true, message: '请选择目标用户', trigger: 'change' }
  ]
}

// 编辑书籍表单验证规则
const editBookRules = {
  novelName: [
    { required: true, message: '请输入书名', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入分类', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  isVip: [
    { required: true, message: '请选择是否VIP', trigger: 'change' }
  ],
  targetUser: [
    { required: true, message: '请选择目标用户', trigger: 'change' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  // 如果是字符串且包含T，则是ISO格式
  if (typeof dateTime === 'string' && dateTime.includes('T')) {
    return dateTime.replace('T', ' ').substring(0, 19)
  }
  // 如果是Date对象
  if (dateTime instanceof Date) {
    const year = dateTime.getFullYear()
    const month = String(dateTime.getMonth() + 1).padStart(2, '0')
    const day = String(dateTime.getDate()).padStart(2, '0')
    const hours = String(dateTime.getHours()).padStart(2, '0')
    const minutes = String(dateTime.getMinutes()).padStart(2, '0')
    const seconds = String(dateTime.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  return dateTime
}

// 搜索书籍
const searchBooks = (keyword) => {
  pagination.pageNum = 1
  fetchBookList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  pagination.pageNum = 1
  fetchBookList()
}

// 获取书籍列表
const fetchBookList = () => {
  loading.value = true
  console.log('Fetching books with params:', {
    keyword: managementTableRef.value?.searchForm.keyword || '',
    pageNum: pagination.pageNum,
    pageSize: pagination.pageSize
  })

  request.get('/api/admin/books/list', {
    params: {
      keyword: managementTableRef.value?.searchForm.keyword || '',
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }
  }).then(response => {
    console.log('Books API response:', response)
    if (response.code === 200) {
      // 修改数据处理逻辑，适配后端实际返回的数据结构
      const data = response.data
      if (data && Array.isArray(data.list)) {
        bookList.value = data.list
        pagination.total = data.total || 0
        console.log(`Loaded ${data.list.length} books, total: ${data.total}`)
      } else {
        // 如果数据结构不符合预期，使用默认值
        bookList.value = []
        pagination.total = 0
        console.warn('Books data structure is not as expected:', data)
      }
    } else {
      ElMessage.error('获取书籍列表失败: ' + response.message)
    }
  }).catch(error => {
    console.error('获取书籍列表失败:', error)
    ElMessage.error('获取书籍列表失败: ' + error.message)
  }).finally(() => {
    loading.value = false
  })
}

// 显示添加书籍对话框
const showAddBookDialog = () => {
  // 重置表单
  Object.assign(addBookForm, {
    novelName: '',
    author: '',
    category: '',
    status: '连载',
    isVip: 0,
    targetUser: 0,
    intro: '',
    coverUrl: '',
    novelUrl: '',
    latestChapter: '',
    chapterUrl: '',
    updateTime: '',
    clickCount: 0,
    subscribeCount: 0,
    recommendCount: 0
  })
  addBookDialogVisible.value = true
}

// 添加书籍
const addBook = () => {
  addBookFormRef.value.validate((valid) => {
    if (valid) {
      request.post('/api/admin/books/add', addBookForm)
        .then(response => {
          if (response.code === 200) {
            ElMessage.success('书籍添加成功')
            addBookDialogVisible.value = false
            fetchBookList()
          } else {
            ElMessage.error('添加书籍失败: ' + response.message)
          }
        })
        .catch(error => {
          ElMessage.error('添加书籍失败: ' + error.message)
        })
    }
  })
}

// 显示编辑书籍对话框
const showEditBookDialog = (book) => {
  // 填充表单数据
  Object.assign(editBookForm, {
    bookId: book.bookId,
    novelName: book.novelName,
    author: book.author,
    category: book.category,
    status: book.status,
    isVip: book.isVip,
    targetUser: book.targetUser,
    intro: book.intro,
    coverUrl: book.coverUrl,
    novelUrl: book.novelUrl,
    latestChapter: book.latestChapter,
    chapterUrl: book.chapterUrl,
    updateTime: book.updateTime,
    clickCount: book.clickCount || 0,
    subscribeCount: book.subscribeCount || 0,
    recommendCount: book.recommendCount || 0
  })
  editBookDialogVisible.value = true
}

// 更新书籍
const updateBook = () => {
  editBookFormRef.value.validate((valid) => {
    if (valid) {
      request.put('/api/admin/books/update', editBookForm)
        .then(response => {
          if (response.code === 200) {
            ElMessage.success('书籍更新成功')
            editBookDialogVisible.value = false
            fetchBookList()
          } else {
            ElMessage.error('更新书籍失败: ' + response.message)
          }
        })
        .catch(error => {
          ElMessage.error('更新书籍失败: ' + error.message)
        })
    }
  })
}

// 删除书籍
const deleteBook = (book) => {
  ElMessageBox.confirm('确定要删除这本书籍吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete(`/api/admin/books/delete/${book.bookId}`)
      .then(response => {
        if (response.code === 200) {
          ElMessage.success('书籍删除成功')
          fetchBookList()
        } else {
          ElMessage.error('删除书籍失败: ' + response.message)
        }
      })
      .catch(error => {
        ElMessage.error('删除书籍失败: ' + error.message)
      })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  console.log('Page size changed to:', val)
  pagination.pageSize = val
  pagination.pageNum = 1 // 重置到第一页
  fetchBookList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  console.log('Current page changed to:', val)
  pagination.pageNum = val
  fetchBookList()
}

// 组件挂载时获取书籍列表
onMounted(() => {
  fetchBookList()
})

// 定义暴露给父组件的方法
defineExpose({
  fetchBookList
})
</script>

<style scoped>
.book-management {
  padding: 20px;
  background-color: #f5f5f5;
  height: 100%;
}

.book-management :deep(.el-card) {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}
</style>